// pages/order/order.js
const {
  formatTime2,
  formatDate3,
  extractAndConvertChineseNumbers,
  extractNumberFromString,
} = require("../../utils/utils");
// 在其他地方获取数据库对象
var esc = require("../../utils/esc.js");
var app = getApp();
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
    return ("00" + bit.toString(16)).slice(-2);
  });
  return hexArr.join("");
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderFoodList: [],
    showModal: false,
    shopPosition: "-1",
    storeOptions: [
      { id: 0, name: "椒麻鸡花溪路店" },
      { id: 1, name: "椒麻鸡大宁店" },
    ],
    //打印机相关
    looptime: 0,
    currentTime: 1,
    lastData: 0,
    oneTimeData: 0,
    buffSize: [],
    buffIndex: 0, //发送字节数下标
    printNum: [],
    printNumIndex: 0,
    printerNum: 1,
    currentPrint: 1,
    isReceiptSend: false,
    isQuery: false,
  },
  receiptData: function (item) {
    wx.showLoading({
      title: "请求中",
    });
    //票据测试
    var that = this;

    var command = esc.jpPrinter.createNew();
    command.init(); //初始化打印机

    command.setPrint(); //打印并换行
    command.setPrint(); //打印并换行
    command.setSelectJustification(1); //居中
    command.setCharacterSize(17); //设置倍高倍宽
    command.setText(item.orderMess);
    command.setPrint(); //打印并换行
    command.setCharacterSize(0); //设置正常大小
    command.setSelectJustification(0); //设置居左

    // command.setText("二维码测试:");
    // command.setPrint();
    // command.setSelectSizeOfModuleForQRCode(5);
    // command.setSelectErrorCorrectionLevelForQRCode(49);
    // command.setStoreQRCodeData("http://www.howbest.cn/cn/");
    // command.setPrintQRCode();

    command.setPrint();
    command.setPrint();
    command.setPrint(); //打印并换行
    command.setPrint(); //打印并换行
    command.setPrint(); //打印并换行
    that.prepareSend(command.getData()); //准备发送数据
    setTimeout(() => {
      wx.hideLoading();
    }, 1000);
  },
  prepareSend: function (buff) {
    //准备发送，根据每次发送字节数来处理分包数量
    //console.log(buff)
    var that = this;
    var time = that.data.oneTimeData;
    var looptime = parseInt(buff.length / time);
    var lastData = parseInt(buff.length % time);
    //console.log(looptime + "---" + lastData)
    that.setData({
      looptime: looptime + 1,
      lastData: lastData,
      currentTime: 1,
    });
    that.Send(buff);
  },
  Send: function (buff) {
    //分包发送
    var that = this;
    var currentTime = that.data.currentTime;
    var loopTime = that.data.looptime;
    var lastData = that.data.lastData;
    var onTimeData = that.data.oneTimeData;
    var printNum = that.data.printerNum;
    var currentPrint = that.data.currentPrint;
    var buf;
    var dataView;
    if (currentTime < loopTime) {
      buf = new ArrayBuffer(onTimeData);
      dataView = new DataView(buf);
      for (var i = 0; i < onTimeData; ++i) {
        dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i]);
      }
    } else {
      buf = new ArrayBuffer(lastData);
      dataView = new DataView(buf);
      for (var i = 0; i < lastData; ++i) {
        dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i]);
      }
    }
    //console.log("第" + currentTime + "次发送数据大小为：" + buf.byteLength)
    wx.writeBLECharacteristicValue({
      deviceId: app.BLEInformation.deviceId,
      serviceId: app.BLEInformation.writeServiceId,
      characteristicId: app.BLEInformation.writeCharaterId,
      value: buf,
      success: function (res) {
        if (currentTime <= loopTime) {
        } else {
          wx.showToast({
            title: "已打印成功",
          });
        }
        console.log(res);
      },
      fail: function (e) {
        wx.showToast({
          title: "打印失败 请在我的界面进行蓝牙配对",
          icon: "none",
        });
        console.log(e);
      },
      complete: function () {
        currentTime++;
        if (currentTime <= loopTime) {
          that.setData({
            currentTime: currentTime,
          });
          that.Send(buff);
        } else {
          if (currentPrint == printNum) {
            that.setData({
              looptime: 0,
              lastData: 0,
              currentTime: 1,
              isReceiptSend: false,
              currentPrint: 1,
            });
          } else {
            currentPrint++;
            that.setData({
              currentPrint: currentPrint,
              currentTime: 1,
            });
            that.Send(buff);
          }
        }
      },
    });
  },
  // 获取添加的数据
  getData() {
    if (this.data.shopPosition == "-1")
      return wx.showToast({
        title: "请选择店铺地址",
        icon: "none",
      });
    wx.showLoading({
      title: "请求中",
    });
    const queryConditions = {
      shopPosition: this.data.shopPosition,
      orderDate: formatDate3(new Date()),
      //or 或的意思 false 或者null
      $or: [{ sendFood: false }, { sendFood: null }],
    };

    console.log("下单列表查询条件: ", queryConditions);
    getApp()
      .getDatabase()
      .collection("orderList")
      .where(queryConditions)

      .limit(100) // 控制获取的记录数量
      .get()

      .then((res) => {
        wx.hideLoading();

        this.setData({
          orderFoodList: res.data,
        });

        if (
          this.data.orderFoodList.length > 0 &&
          this.data.orderFoodList.some((item) => !item.clickCookFood)
        ) {
          console.log("再次播放/////////////");
          this.innerAudioContext.play();
        }
        this.processOrderFoodList();
        // console.log("再次请求成功" + JSON.stringify(res));
      });
  },
  processOrderFoodList() {
    const itemsToPrint = this.data.orderFoodList.filter(
      (item) => !item.clickCookFood || item.clickCookFood === null
    );
    let index = 0;

    const printNextItem = () => {
      if (index < itemsToPrint.length) {
        this.automaticPrint(itemsToPrint[index]);
        index++;
        setTimeout(printNextItem, 2000); // 1秒后调用下一次
      }
    };

    if (itemsToPrint.length > 0) {
      printNextItem();
    }
  },
  //自动打印操作
  automaticPrint(item) {
    console.log("自动打印操作------------------>");

    this.receiptData(item);

    wx.showLoading({
      title: "请求中",
    });

    getApp()
      .getDatabase()
      .collection("orderList")
      .doc(item._id)
      .update({
        data: {
          clickCookFood: true,
        },
        success: (res) => {
          // 异步更新本地数据
          setTimeout(() => {
            const updatedOrderFoodList = this.data.orderFoodList.map(
              (order) => {
                if (order._id === item._id) {
                  return { ...order, clickCookFood: true };
                }
                return order;
              }
            );
            this.setData({
              orderFoodList: updatedOrderFoodList,
            });
            wx.hideLoading();
          }, 0);
        },
        fail: (err) => {
          wx.hideLoading();
        },
      });
  },
  //点击做餐
  clickCookFood(e) {
    const item = e.currentTarget.dataset.item;

    this.receiptData(item);

    if (item.clickCookFood === true) return;
    console.log("点击做餐////////////////////" + item.clickCookFood);
    wx.showLoading({
      title: "请求中",
    });

    getApp()
      .getDatabase()
      .collection("orderList")
      .doc(item._id)
      .update({
        data: {
          clickCookFood: true,
        },
        success: (res) => {
          // 异步更新本地数据
          setTimeout(() => {
            const updatedOrderFoodList = this.data.orderFoodList.map(
              (order) => {
                if (order._id === item._id) {
                  return { ...order, clickCookFood: true };
                }
                return order;
              }
            );
            this.setData({
              orderFoodList: updatedOrderFoodList,
            });
            wx.hideLoading();
          }, 0);
        },
        fail: (err) => {
          wx.hideLoading();
        },
      });
  },
  //点击出餐
  sendFood(e) {
    const item = e.currentTarget.dataset.item;
    if (item.clickCookFood == false || item.clickCookFood == null) {
      return wx.showToast({
        title: "请先点击做餐按钮开始做餐！！！！",
        icon: "none",
        duration: 2000,
      });
    }
    wx.showLoading({
      title: "请求中",
    });
    getApp()
      .getDatabase()
      .collection("orderList")
      .doc(item._id)
      .update({
        data: {
          sendFood: true,
        },
        success: (res) => {
          this.getData();
          wx.hideLoading();
        },
        fail: (err) => {
          wx.hideLoading();
        },
      });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onReady: function () {
    var list = [];
    var numList = [];
    var j = 0;
    for (var i = 20; i < 200; i += 10) {
      list[j] = i;
      j++;
    }
    for (var i = 1; i < 10; i++) {
      numList[i - 1] = i;
    }
    this.setData({
      buffSize: list,
      oneTimeData: list[0],
      printNum: numList,
      printerNum: numList[0],
    });
  },
  onLoad: function (options) {
    app.BLEInformation.platform = app.getPlatform();
    // 创建内部音频上下文对象
    this.innerAudioContext = wx.createInnerAudioContext();
    this.innerAudioContext.src =
      "https://7869-xiegang-3gf3n6ez27c3c8e1-1329835049.tcb.qcloud.la/order_come.mp3?sign=0623466440838fb5959800484281cb50&t=1732506825";

    // 监听播放结束事件
    this.innerAudioContext.onEnded(() => {
      console.log("语音播放结束");
    });

    // 监听播放错误事件
    this.innerAudioContext.onError((res) => {
      console.error("语音播放错误", res);
    });

    // 监听播放加载事件
    this.innerAudioContext.onCanplay(() => {
      console.log("语音加载成功");
    });

    // 监听播放进度事件
    this.innerAudioContext.onTimeUpdate(() => {
      // console.log("当前播放时间", this.innerAudioContext.currentTime);
    });

    // 页面加载时启动定时器
    this.startTimer();
  },

  onUnload: function () {
    console.log("onUnloadonUn关闭蓝牙成功");
    wx.closeBLEConnection({
      deviceId: app.BLEInformation.deviceId,
      success: function (res) {
        console.log("关闭蓝牙成功");
      },
    });
  },

  startTimer: function () {
    // 启动定时器
    this.timer = setInterval(() => {
      this.getData();
    }, 3000000); // 30000毫秒 = 30秒
  },

  clearTimer: function () {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面加载时读取本地存储的 shopPosition
    const savedShopPosition = wx.getStorageSync("shopPosition");
    if (savedShopPosition !== "") {
      this.setData({ shopPosition: savedShopPosition });
      setTimeout(() => {
        this.getData();
      }, 500);
    }
  },

  // 显示模态框
  showModal: function () {
    this.setData({ showModal: true });
  },
  // 关闭模态框
  closeModal: function () {
    this.setData({ showModal: false });
  },
  // 确认选择
  onConfirm: function (e) {
    const selectedId = e.detail.selectedId;
    console.log("用户选择的店铺ID:", selectedId);
    wx.setStorageSync("shopPosition", selectedId + "");
    this.setData({ showModal: false, shopPosition: selectedId + "" });
    this.getData();
    // 这里可以处理用户选择的店铺ID
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    // 页面卸载时清除定时器
    this.clearTimer();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showLoading({
      title: "加载中",
    });

    // 模拟异步请求
    setTimeout(() => {
      // 更新数据
      this.getData();

      // 停止下拉刷新
      wx.stopPullDownRefresh();
    }, 2000);
  },
});
